package zsc.liangyi.blog.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zsc.liangyi.blog.dao.ArticleDao;
import zsc.liangyi.blog.dao.CategoryDao;
import zsc.liangyi.blog.dao.CommentMapper;
import zsc.liangyi.blog.dao.StatisticMapper;
import zsc.liangyi.blog.model.domain.Article;
import zsc.liangyi.blog.model.domain.Statistic;
import zsc.liangyi.blog.service.ArticleService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//实现接口业务逻辑
@Service
@Transactional
@CacheConfig(cacheNames = "article")
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleDao articleMapper;
    @Autowired
    private StatisticMapper statisticMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private UserServiceImpl userService;
    @Resource
    private RedisTemplate redisTemplate;

    //分页查询文章列表
    private int HEAT_RANKING_NUM=10;

    @Override
    public Article selectArticleWithId(Integer id) {
        Article article=null;
//        Object obj=redisTemplate.opsForValue().get("article_"+id);
        Object obj=null;
        if(obj!=null){
            return (Article)obj;
        }else{
            //redis为空，则去数据库查找
            article=articleMapper.selectArticleWithId(id);
            if(article!=null){
                redisTemplate.opsForValue().set("article_"+id,article,1000, TimeUnit.SECONDS);
                return article;
            }else{
                return null;
            }
        }
    }

    @Override
    public PageInfo<Article> selectArticleWithPage(Integer page, Integer count) {
        PageHelper.startPage(page,count);
        List<Article> articleList=articleMapper.selectArticleWithPage();
        //封装文章统计数据
        wrapArticle(articleList);
        PageInfo<Article> pageInfo=new PageInfo<>(articleList);
        return pageInfo;
    }

    @Override
    public PageInfo<Article> selectArticleWithPageByUserId(Integer userId,Integer page, Integer count) {
        PageHelper.startPage(page,count);
        List<Article> articleList=articleMapper.selectArticleWithPageByUserId(userId);
        //封装文章统计数据
        wrapArticle(articleList);
        PageInfo<Article> pageInfo=new PageInfo<>(articleList);
        return pageInfo;
    }

    @Override
    public PageInfo<Article> selectArticleWithCollectByUserId(Integer userId,Integer page, Integer count) {
        PageHelper.startPage(page,count);
        List<Article> articleList=articleMapper.selectArticleWithCollectByUserId(userId);
        //封装文章统计数据
        wrapArticle(articleList);
        PageInfo<Article> pageInfo=new PageInfo<>(articleList);
        return pageInfo;
    }


    //获取文章热度信息排名
    @Override
    public List<Article> getHeatArticle() {
        List<Statistic> statisticList=statisticMapper.getStatistic();
        List<Article> articleList=new ArrayList<>();
        Article article=new Article();
        for(int i=0;i<statisticList.size();i++){
            article=articleMapper.selectArticleWithId(statisticList.get(i).getArticleId());
            article.setHits(statisticList.get(i).getHits());
            article.setCommentsNum(statisticList.get(i).getCommentsNum());
            articleList.add(article);
            if(i>=HEAT_RANKING_NUM-1){
                break;
            }
        }
        return articleList;
    }


    //搜索文章
    @Override
    public PageInfo<Article> selectArticleWithKeyWord(Integer page, Integer count,String keyword) {
        PageHelper.startPage(page,count);
        List<Article> articleList=articleMapper.selectArticleWithKeyword(keyword);
        wrapArticle(articleList);
        PageInfo<Article> pageInfo=new PageInfo<>(articleList);
        return pageInfo;
    }

    @Override
    public void publish(Article article) {
        //转换表情格式，设置发布日期，点击量，评论数
        article.setContent(EmojiParser.parseToAliases(article.getContent()));
        article.setCreated(new Date());
        article.setHits(0);
        article.setCommentsNum(0);
        //插入数据
        articleMapper.publishArticle(article);
        statisticMapper.addStatistic(article);
    }

    @Override
    public void updateArticleWithId(Article article) {
        article.setModified(new Date());
        articleMapper.updateArticleWithId(article);
        redisTemplate.delete("article_"+article.getId());
    }

    @Override
    public void deleteArticleWithId(Integer id) {
        //删除文章同时，删除redis里的缓存
        articleMapper.deleteArticleWithId(id);
        redisTemplate.delete("article_"+id);
        //删除统计数据
        statisticMapper.deleteStatisticWithId(id);
        //同时删除评论
        commentMapper.deleteCommentWithId(id);
    }

    @Override
    public List<Article> selectArticleWithColumn(String column, Object value) {
        List<Article> articleList=articleMapper.selectArticleWithColumn(column,value);
        wrapArticle(articleList);
        return articleList;
    }

    //封装文章统计数据
    private void wrapArticle(List<Article> articleList){
        for(int i=0;i<articleList.size();i++){
            Article article=articleList.get(i);
            Statistic statistic=statisticMapper.selectStatisticWithArticleId(article.getId());
            //获取点击率
            article.setHits(statistic.getHits());
            //获取所属用户
            article.setUsername(userService.selectUserWithId(article.getUserId()).getUsername());
            //获取评论数
            article.setCommentsNum(statistic.getCommentsNum());
            //获取分类
            article.setCategoryName(categoryDao.queryById(article.getCategoryId()).getCategoryName());
        }
    }

}
